package k2;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class Cache {
	private Utils utils = new Utils();
	public String readFile() throws IOException{
		FileInputStream fstream = null;
		try {
			fstream = new FileInputStream("studentInfo.txt");
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			return br.readLine();
		} catch (FileNotFoundException e) {
			return null;
		}
	}
	public void writeFile(String inputLine) throws IOException{
		 FileWriter fstream = null;
		try {
			fstream = new FileWriter("studentInfo.txt");
		} catch (IOException e) {
			System.err.println("Error: " + e.getMessage());
		}
		 BufferedWriter out = new BufferedWriter(fstream);
		 out.write(inputLine);
		 out.close();
	}
	public boolean checkForUpdate(Student student) throws IOException{
		String[] entryArray = utils.substringsBetween(readFile(), "<entry>", "</entry>");
		String[] title = null;
		String[] update = null;
		if(entryArray != null){
			for(String entry : entryArray){
				title = utils.substringsBetween(entry, "<title type='text'>", "</title>");
				update = utils.substringsBetween(entry, "<updated>", "</updated>");
				if(student.getTitle().equalsIgnoreCase(title[0])){
					if(student.getUpdate().equalsIgnoreCase(update[0])){
						return false;
					}
					break;
				}
			}
		}
		return true;
	}
}
